package com.shihang.core.apollo.config;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.shihang.core.base.api.ApolloDataApi;
import com.shihang.core.apollo.util.JacksonUtil;
import com.shihang.core.base.util.ObjectUtil;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class ShihangApolloDataImpl implements ApolloDataApi {


    private Config config = ConfigService.getAppConfig();

    private org.slf4j.Logger logger = LoggerFactory.getLogger(ShihangApolloDataImpl.class);


    @Override
    public String getProperty(String key) {
        ObjectUtil.checkArgument(key);
        return config.getProperty(key, "");
    }

    @Override
    public Integer getIntProperty(String key) {
        ObjectUtil.checkArgument(key);
        return config.getIntProperty(key, 0);
    }

    @Override
    public Long getLongProperty(String key) {
        ObjectUtil.checkArgument(key);
        return config.getLongProperty(key, 0L);
    }

    @Override
    public Short getShortProperty(String key) {

        ObjectUtil.checkArgument(key);
        short defaultShort = 0;
        return config.getShortProperty(key, defaultShort);
    }

    @Override
    public Float getFloatProperty(String key) {
        ObjectUtil.checkArgument(key);
        return config.getFloatProperty(key, 0F);
    }

    @Override
    public Double getDoubleProperty(String key) {
        ObjectUtil.checkArgument(key);
        return config.getDoubleProperty(key, 0d);
    }

    @Override
    public Byte getByteProperty(String key) {
        ObjectUtil.checkArgument(key);
        Byte defaultValue = 0;
        return config.getByteProperty(key, defaultValue);
    }

    @Override
    public Boolean getBooleanProperty(String key) {
        ObjectUtil.checkArgument(key);
        return config.getBooleanProperty(key, Boolean.FALSE);
    }

    @Override
    public Date getDateProperty(String key, String format) {
        ObjectUtil.checkArgument(key);
        return config.getDateProperty(key, new Date());
    }

    @Override
    public <T> T getObject(String key, Class<T> clazz) {
        ObjectUtil.checkArgument(key, clazz);
        return JacksonUtil.stringToObject(config.getProperty(key, ""), clazz);
    }

    @Override
    public <T> List<T> getList(String key, Class<T> clazz) {
        ObjectUtil.checkArgument(key, clazz);
        try {
            return JacksonUtil.stringToCollection(config.getProperty(key, ""), List.class, clazz);
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }
    }
}
